<template>
    <div class="login-wrap">
        <div class="ms-title">{{ $title }}</div>
        <div class="ms-login">
            <el-form :model="ruleForm3" :rules="rules3" ref="ruleForm3" label-width="0px" class="demo-ruleForm">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm3.username" placeholder="username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" placeholder="password" v-model="ruleForm3.password" @keyup.enter.native="submitForm('ruleForm3')"></el-input>
                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm('ruleForm3')">登录</el-button>
                </div>
                <div class="register"><router-link :to="{ path: '/RegisterAll'}">注册店铺</router-link></div>
                <!-- <span style="font-size:12px;line-height:30px;color:#999;cursor:pointer;" @click="changePwd">忘记密码</span> -->
            </el-form>
        </div>
        <div>
            <!-- <el-dialog title="找回密码"  :visible.sync="dialogVisible" size="tiny" >
                 <el-form :model="ruleForm" ref="ruleForm" label-position="top" label-width="" class="demo-ruleForm">
                    <el-form-item prop="phone" label="验证手机号码">
                        <el-input v-model="ruleForm.phone" placeholder="phone" style="width:65%"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="valicode">
                        <el-input v-model="ruleForm.valicode" style="width:200px;float:left;"></el-input>
                        <el-button  style="float:left;margin:0 10px" @click="sendvalicode" :disabled="valicodeIsDisable">{{valicodetext}}</el-button>
                    </el-form-item>
                    <el-form-item label="" prop="">
                        <el-button type="primary" @click="next">下一步</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog> -->
            <!-- <el-dialog title="修改密码" :visible.sync="dialogVisible2" size="tiny" >
                <el-form :model="ruleForm2" :rule="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="新密码" prop="password">
                    <el-input type="password" v-model="ruleForm2.password"></el-input>
                  </el-form-item>
                  <el-form-item label="重复密码" prop="repassword">
                    <el-input type="password" v-model="ruleForm2.repassword"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="changePassword">修改密码</el-button>
                  </el-form-item>
                </el-form>
            </el-dialog> -->
        </div>
    </div>
</template>
<script>
import $ from 'jquery';
export default {

    data: function() {
        return {
            ruleForm3: {
                username: '',
                password: ''
            },
            rules3: {
                username: [{
                    required: true,
                    message: '请输入用户名',
                    trigger: 'blur'
                }],
                password: [{
                    required: true,
                    message: '请输入密码',
                    trigger: 'blur'
                }]
            },

            phone:'',
            dialogVisible:false,
            valicodeIsDisable:false,
            valicodetext:'发送验证码',
            validtime:60,

            ruleForm:{
                valicode:'',
                phone:'',
            },
            rules:{
                valicode:[
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    // {validator: valid, trigger: 'blur'},
                ],
                phone:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    // {validator: validPhone, trigger: 'blur'}
                ]
            },
            ruleForm2:{
                password:'',
                repassword:'',
            },
            rules2:{
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 18, message: '密码长度在 6 到 18 个字符', trigger: 'blur' }
                ],
                repassword: { validator: this.validPass, trigger: 'blur' }
            },
            dialogVisible:false,
            dialogVisible2:false,
        }
    },
    create(){
        
    },
    mounted(){
        // var loginUrl = window.location.host;
        // localStorage.setItem("login_url",loginUrl);
        // var isForbidden = localStorage.getItem("is_forbidden");
        // if (isForbidden) {
        //     $.tooltip("请重新登录哦", 3000);
        // }
        
    },
    methods: {
        submitForm(formName) {
            const self = this;
            self.$refs[formName].validate((valid) => {
                if (valid) {
                    var appId = btoa(self.ruleForm3.username + ":" + self.ruleForm3.password + ":" + "admin.test.cn");
                    localStorage.setItem("App_Http_Config_2387fei89354hng4",appId);
                    $.ajax({
                        type: 'POST',
                        url: this.$host + "/login",
                        dataType: 'json',
                        async: false,
                        crossDomain: true,
                        headers: {
                            "Authorization": "Basic " + appId,
                            'Access-Control-Allow-Origin': '*',
                            'Access-Control-Allow-Credentials': true,
                            'Access-Control-Allow-Headers': "x-requested-with"
                        },
                        success: function(data) {
                            if (data.code == 1000) {
                                $.tooltip('登录成功', 2500, true);
                                localStorage.removeItem('is_forbidden');
                                localStorage.setItem('user_token', data.data);
                                localStorage.setItem('ms_username', self.ruleForm3.username);
                                self.$router.push('/index');
                            }else {
                                $.tooltip(data.message, 3000);
                            }
                            
                        },
                        error: function(xhr, textStatus, errorThrown) {
                            if (xhr.status == 401) {
                                $.tooltip("用户名或密码错误", 3000);
                            } else if (xhr.status == 403) {
                                $.tooltip("用户已被禁用", 3000);
                            } else {
                                $.tooltip("网络服务器错误", 3000);
                            }
                        },
                        beforeSend: function(xhr) {
                            xhr.withCredentials = true
                        }
                    });
                    return true;
                } else {
                    return false;
                }
            });
        },
        changePwd(){
            var self=this;
            self.ruleForm.phone='';
            self.ruleForm.valicode='';
            self.ruleForm2.password='';
            self.ruleForm2.repassword='';
            self.dialogVisible=true;
        },
        sendvalicode(){
            var self=this;
            var valid=self.validPhone;
            var phone=self.ruleForm.phone;
            if(!phone||phone.length!=11){
                $.tooltip("请输入正确的手机号码", 3000);
                return;
            }
            self.myajax("/user/existAndCheckAdmin",{phone:phone},function(data){
                if (data.code === 2000) {
                    var dto = data.data;
                    if (dto.exist && !dto.admin) {
                        self.myajax("/user/sendPasswordCode",{phone:phone},function(data){
                            if(data.code==2000){
                                self.valicodeIsDisable=true;
                                self.validtime=60;
                                self.valicodetext="剩余"+self.validtime+"s";
                                window.interVali=setInterval(self.valitime,1000);
                               $.tooltip("发送成功",3000,true);
                            }else{
                                $.tooltip(data.msg,3000);
                                clearInterval(window.interVali);
                                self.valicodeIsDisable=false;
                                self.valicodetext="发送验证码";
                           }
                        });
                    }else{
                        $.tooltip("请输入正确的手机号码", 3000);
                    }
                }else {
                    $.tooltip("请输入正确的手机号码", 3000);
                }
            })
            
        },
        valitime(){
            var self=this;
            self.valicodetext="剩余"+self.validtime+"s";
            self.validtime=self.validtime-1;
            if(self.validtime<0){
                self.valicodeIsDisable=false;
                clearInterval(window.interVali);
                self.valicodetext="发送验证码";
            }
        },
        next(){
            var self=this;
            this.$refs['ruleForm'].validate((valid) => {
                if(valid){
            //         ruleForm:{
            //     valicode:'',
            //     phone:'',
            // },
                    var phoneCheck = self.validPhone(null,self.ruleForm.phone,function(){});
                    if (!phoneCheck) {
                        $.tooltip("请输入正确的手机号", 3000);
                        return;
                    }
                    var valicodeCheck = self.validcode(null,self.ruleForm.valicode,function(){});
                    if (!valicodeCheck) {
                        $.tooltip("请输入正确的验证码", 3000);
                        return;
                    }
                    this.dialogVisible=false;
                    this.dialogVisible2=true;
                }
            });
        },
        changePassword(){
            var self=this;
            // var valicode=self.ruleForm.valicode;
            // ruleForm2:{
            //     password:'',
            //     repassword:'',
            // },
            var password=self.ruleForm2.password;
            var rePassword = self.ruleForm2.repassword
            var phone=self.ruleForm.phone;
            var data={
                // valicode:valicode,
                password:rePassword,
                phone:phone,
            }
            this.$refs['ruleForm2'].validate((valid) => {
                if(valid){
                    var passCheck = self.validPass(null,password,function(){});
                    if (!passCheck) {
                        $.tooltip("请输入6-18位密码", 3000);
                        return;
                    }
                    var rePassCheck = self.validRePass(null,rePassword,function(){});
                    if (!rePassCheck) {
                        $.tooltip("重复密码不正确", 3000);
                        return;
                    }
                    self.myajax("/user/changePassword",data,function(data){
                        if(data.code==2000){
                            $.tooltip('修改成功', 2500, true);
                            self.dialogVisible=false;
                            self.dialogVisible2=false;
                        }else{
                            $.tooltip(data.msg, 3000);
                        }
                    })
                }
            });

        },
        //验证码检查
        validcode(rule, value, callback){
            var self=this;
            if(self.ruleForm.phone==''||self.ruleForm.phone.length!=11){
              callback(new Error('请先输入手机号'));
              return false;
            }
            if (value === '') {
              callback(new Error('请输入验证码'));
              return false;
            } else {
                if(value.length!=6){
                    callback(new Error('请输入正确的验证码'));
                    return false;
                }else{
                    var data={code:value,phone:self.ruleForm.phone};
                    var backcode=true;
                    self.myajax("/user/valiRePassword",data,function(data){
                        if(data.code==2000){
                            callback();
                        }else{
                            callback(new Error(data.msg));
                            backcode=false;
                        }
                    });
                    return backcode;
                }
            }
        },
        validPass(rule, value, callback){
            if (value === '') {
              callback(new Error('请输入密码'));
              return false;
            } else {
                if (value.length <6 || value.length >18 ) {
                    callback(new Error('密码必须在6-18位之间'));
                    return false;
                }else{
                    return true;
                }
            }
        },
        validRePass(rule, value, callback){
            if (value === '') {
              callback(new Error('请重复密码'));
              return false;
            } else {
                if (this.ruleForm.password !== '') {
                    if(value!=this.ruleForm2.password){
                        callback(new Error('重复密码不正确'));
                        return false;
                    }
                    callback();
                    return true;
                }else{
                    return false;
                }
            }
        },
        validPhone(rule, value, callback){
            var self=this;
            var phone=self.ruleForm.phone;
            if(!phone||phone.length!=11){
                callback(new Error('请输入正确的手机号'));
                return false;
            }
            var backcode=false;
            self.myajax("/user/exist",{phone:phone},function(data){
                if(data.code==2006){
                    backcode=true;
                    callback();
                }else{
                    backcode=false;
                    callback(new Error('用户名不存在'));
                }
            })
            return backcode;
        },
    }
}
</script>
<style scoped>
.register a{
    text-align: right;
    padding-top:10px;
    color: #8e8e8e;
    display: block;
}
.login-wrap {
    position: relative;
    width: 100%;
    height: 100%;
}

.ms-title {
    position: absolute;
    top: 50%;
    width: 100%;
    margin-top: -230px;
    text-align: center;
    font-size: 30px;
    color: #fff;
}

.ms-login {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 300px;
    height: 160px;
    margin: -150px 0 0 -190px;
    padding: 40px;
    border-radius: 5px;
    background: #fff;
}

.login-btn {
    text-align: center;
}

.login-btn button {
    width: 100%;
    height: 36px;
}
</style>
